Circular array loop¶
Time: O(N); Space: O(1); medium
You are given a circular array nums of positive and negative integers.
If a number k at an index is positive, then move forward k steps.
Conversely, if it’s negative (-k), move backward k steps.
Since the array is circular, you may assume that the last element’s next element is the first element, and the first element’s previous element is the last element.
Determine if there is a loop (or a cycle) in nums.
A cycle must start and end at the same index and the cycle’s length > 1.
Furthermore, movements in a cycle must all follow a single direction.
In other words, a cycle must not consist of both forward and backward movements.
Example 1:
Input: nums = [2,-1,1,2,2]
Output: True
Explanation:
There is a cycle, from index 0 -> 2 -> 3 -> 0. The cycle’s length is 3.
Example 2:
Input: nums = [-1,2]
Output: False
Explanation:
The movement from index 1 -> 1 -> 1 … is not a cycle, because the cycle’s length is 1. By definition the cycle’s length must be greater than 1.
Example 3:
Input: nums = [-2,1,-1,-2,-2]
Output: False
Explanation:
The movement from index 1 -> 2 -> 1 -> … is not a cycle, because movement from index 1 -> 2 is a forward movement, but movement from index 2 -> 1 is a backward movement. All movements in a cycle must follow a single direction.
Constraints:
-1000 ≤ nums[i] ≤ 1000
nums[i] ≠ 0
1 ≤ len(nums) ≤ 5000
Follow up:
Could you solve it in O(n) time complexity and O(1) extra space complexity?
[1]:
class Solution1(object):
"""
Time: O(N)
Space: O(1)
"""
def circularArrayLoop(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
def next_index(nums, i):
return (i + nums[i]) % len(nums)
for i in range(len(nums)):
if nums[i] == 0:
continue
slow, fast = i, i
while nums[next_index(nums, slow)] * nums[i] > 0 and \
nums[next_index(nums, fast)] * nums[i] > 0 and \
nums[next_index(nums, next_index(nums, fast))] * nums[i] > 0:
slow = next_index(nums, slow)
fast = next_index(nums, next_index(nums, fast))
if slow == fast:
if slow == next_index(nums, slow):
break
return True
slow, val = i, nums[i]
while nums[slow] * val > 0:
tmp = next_index(nums, slow)
nums[slow] = 0
slow = tmp
return False
[2]:
s = Solution1()
nums = [2,-1,1,2,2]
assert s.circularArrayLoop(nums) == True
nums = [-1,2]
assert s.circularArrayLoop(nums) == False
nums = [-2,1,-1,-2,-2]
assert s.circularArrayLoop(nums) == False